#!/usr/bin/env python
# coding:utf-8

import sys
import os
from filerepo import FileRepoService
from filerepo.ttypes import RepoType
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from consts import TEMP_PATH

def write_apk_file(result, apkHash):
    file_path = TEMP_PATH + apkHash+".apk"
    if not os.path.exists(file_path):
        file = open(file_path, "w")
        file.write(result)
        file.close()
        return file_path

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print "Usage: apk_fetcher.py <apk_hash>"
        exit(0)

    apkHash = sys.argv[1]
    file_path = apkHash + ".apk"

    # print apkHash
    if os.path.exists(file_path):
        print "apk exist: "+file_path
        exit(0)

    # Make socket
    transport = TSocket.TSocket('10.141.209.135', 9999)

    # Wrap in a protocol
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    transport.open()
    # Create a client to use the protocol encoder
    client = FileRepoService.Client(protocol)

    result = client.fetch(RepoType.APK_REPO, apkHash)
    transport.close()

    apk_path = write_apk_file(result, apkHash)
    print "write apk to :"+apk_path